// pages/user-center/message-center/message-center.js
const app = getApp();
const request = require('../../../utils/request.js');
const config = require('../../../utils/config.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageNum: 1,
    pageSize: 10,
    messageList: [],
    hasResult: true
  },

  /**
   * 获取用户回复帖子的消息
   */
  getReplyPostList(pageNum, pageSize){
    let that = this;
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL + 'comment/listCommentToSelfPost?pageNum=' + pageNum + '&pageSize=' + pageSize;
    return request.requestGetApi(url, token, {}, 'application/json');
  },

  /**
   * 获取用户回复评论的消息
   */
  getReplyCommentList(pageNum, pageSize){
    let that = this;
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL + 'comment/listCommentToSelf?pageNum=' + pageNum + '&pageSize=' + pageSize;
    return request.requestGetApi(url, token, {}, 'application/json')
  },

  /**
   * 合并和排序消息列表
   */
  async concatMessageList(pageNum, pageSize){
    let that = this;
    let arr = [this.getReplyPostList(pageNum, pageSize), this.getReplyCommentList(pageNum, pageSize)];
    let tmp = [];
    let hasResult = false;
    wx.showLoading({
      title: '加载ing'
    });
    await Promise.all(arr).then((res)=>{
      res.forEach((item, index)=>{
        if(item.status === config.STATUS_OK){
          hasResult = (item.data.rows.length >= that.data.pageSize) || hasResult;
          tmp = tmp.concat(item.data.rows);
        }
      })
    }).catch(err=>{
      app.failFun(err);
    });
    tmp.sort((a, b)=>{
      return Date.parse(b.createTime) - Date.parse(a.createTime);
    });
    this.setData({
      messageList: this.data.messageList.concat(tmp),
      hasResult
    });
    wx.hideLoading();
  },

  /**
   * 清空未读消息数量
   */
  clearUnreadCount(){
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL + 'comment/clearUnreadCount';
    request.requestGetApi(url, token, {}, 'application/json')
  },

  /**
   * 跳转到帖子详情页
   */
  toPostInfo(e){
    wx.navigateTo({
      url: '/pages/post/post?postId=' + e.currentTarget.dataset.postid
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.concatMessageList(this.data.pageNum, this.data.pageSize);
    this.clearUnreadCount();
  },
  
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      pageNum: 1,
      messageList: []
    });
    this.concatMessageList(this.data.pageNum, this.data.pageSize);

    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(!this.data.hasResult){
      return;
    }
    this.setData({
      pageNum: this.data.pageNum + 1
    });
    this.concatMessageList(this.data.pageNum, this.data.pageSize);
  }
})